package org.canaan.http.core.get;

import org.apache.http.client.methods.HttpGet;
import org.apache.http.cookie.Cookie;
import org.apache.http.util.EntityUtils;
import org.canaan.http.HttpResponse;
import org.canaan.http.core.AbstractHttpClient;
import org.canaan.http.urlpair.core.UrlPair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;

/**
 * get 请求
 * @author Canaan
 * @date 2017/8/9
 */
public class GetClient  extends AbstractHttpClient <Object>{
    private final Logger logger = LoggerFactory.getLogger(GetClient.class);
    GetClient(GetHttpBuilder builder) {
        super(builder);
    }

    @Override
    public HttpResponse execute(String url, Object param) throws IOException {

        HttpGet httpGet = null;
        try {
            //添加参数
            if (param != null) {
                String paramString = UrlPair.toURLPairString(param);
                StringBuilder stringBuilder = new StringBuilder(paramString);
                if (url.contains("?")) { //已经有参数了
                    if(url.endsWith("&")){
                        stringBuilder.insert(0, url);
                    }else{
                        stringBuilder.insert(0, "&").insert(0,url);
                    }
                } else {
                    stringBuilder.insert(0, "?").insert(0, url);
                }
                url = stringBuilder.toString();
            }

            httpGet = new HttpGet(url);
            httpGet.setConfig(this.requestConfig);
            //添加cookie
            if (this.cookies != null && this.cookies.size() != 0) {
                StringBuilder cookiesBuilder = new StringBuilder();
                for (String str : this.cookies.keySet()) {
                    cookiesBuilder.append(str).append("=").append(this.cookies.get(str)).append(";");
                }
                cookiesBuilder.deleteCharAt(cookiesBuilder.length() - 1);
                httpGet.setHeader("Cookie", cookiesBuilder.toString());
            }

            //设置请求头
            if (this.header != null && this.header.size() != 0) {
                for (String str : this.header.keySet()) {
                    httpGet.setHeader(str, this.header.get(str));
                }
            }

            // 执行请求
            long begin = System.currentTimeMillis();
            this.response = this.httpClient.execute(httpGet);
            long end = System.currentTimeMillis();
            //获取 result 返回数据
            String responseData = "";
            if (this.response.getEntity() != null) {
                responseData =  EntityUtils.toString(response.getEntity(), "UTF-8");
            }
            HttpResponse _response = new HttpResponse(response);
            //发费时间计算
            _response.setSpendTime(end - begin);
            //cookies值
            if (cookieStore != null) {
                _response.setCookies(cookieStore.getCookies());
            } else {
                _response.setCookies(new ArrayList<Cookie>());
            }
            //返回数据
            _response.setData(responseData);
            //http状态
            _response.setHttpStatus(response.getStatusLine().getStatusCode());
            return _response;
        } finally {
            try {
                if (httpGet != null) {
                    httpGet.releaseConnection();
                    httpGet = null;
                }
            } catch (Exception e) {
                logger.error("", e);
            }
        }
    }


    public static GetHttpBuilder custom() {
        return new GetHttpBuilder();
    }

}
